<script lang="ts" setup name="TenantEditModal">
import { ref } from 'vue'
import { ikDate } from 'iking-utils'
import { tenantApi } from '@/MainApp/apis/tenant'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formKey: {
    type: Object,
    default: () => { }
  },
  editData: {
    type: Object,
    default: () => null
  }
})
const emits = defineEmits<{
  (e: 'update:visible', bool: boolean): void
  (e: 'dataChange'): void
}>()
const { dialog, t } = useConfig()
const { lenContent, lenName, lenShort } = useLength()
const { msgError, msgSuccess } = useMessage()
const dVisible = ref(false)
// 新增、修改
const placeholder = {
  name: '请输入租户名称',
  type: '请选择租户类型',
  code: '请输入租户Code(不能重复)',
  status: '请选择租户状态',
  tenantDomain: '请输入租户域名',
  endDate: '请输入结束日期',
  startDate: '请输入开始日期'
}

const tenantState = reactive({
  title: '新增租户',
  loading: false,
  form: { ...props.formKey }
})
enum EStatus {
  '冻结' = 'FREEZE',
  '正常' = 'NORMAL'
}

watch(() => tenantState.form.status, () => {
  tenantRef.value?.validateField(['startDate', 'endDate'])
  // tenantState.form.startDate = ''
  // tenantState.form.endDate = ''
})

const validStartDate = (rule: any, val: any, cb: (arg0?: string) => void) => {
  const nowDate = new Date(`${ikDate.toDate()} 00:00:00`)
  const sDate = val ? new Date(`${val} 00:00:00`) : null
  if (tenantState.form.status === EStatus.冻结) {
    if (sDate && sDate <= nowDate) {
      tenantState.form.startDate = ''
      cb('冻结状态下，租户开始日期需晚于当前日期')
    }
    else {
      cb()
    }
  }
  else if (tenantState.form.status === EStatus.正常) {
    if (sDate && sDate > nowDate) {
      tenantState.form.startDate = ''
      cb('正常状态下，租户开始日期不能晚于当前日期')
    }
    else {
      cb()
    }
  }
  else {
    cb()
  }
}
const checkStartDate = () => {
  const nowDate = new Date(`${ikDate.toDate()} 00:00:00`)
  const sDate = tenantState.form.startDate ? new Date(`${tenantState.form.startDate} 00:00:00`) : null
  const eDate = tenantState.form.endDate ? new Date(`${tenantState.form.endDate} 00:00:00`) : null
  if (!tenantState.form.endDate) {
    if (sDate && sDate > nowDate)
      tenantState.form.status = EStatus.冻结

    else
      tenantState.form.status = EStatus.正常
  }
  else {
    if (sDate && sDate > nowDate)
      tenantState.form.status = EStatus.冻结
    else if (sDate && sDate <= nowDate && (eDate && (eDate > nowDate)))
      tenantState.form.status = EStatus.正常
    else if (sDate && sDate >= nowDate && (eDate && (eDate === nowDate)))
      tenantState.form.status = EStatus.正常
    else if (eDate && (eDate < nowDate))
      tenantState.form.status = EStatus.冻结
  }
}
const checkEndDate = () => {
  const nowDate = new Date(`${ikDate.toDate()} 00:00:00`)
  const eDate = tenantState.form.endDate ? new Date(`${tenantState.form.endDate} 00:00:00`) : null

  if (!tenantState.form.startDate) {
    if (eDate && eDate >= nowDate)
      tenantState.form.status = EStatus.正常
    else
      tenantState.form.status = EStatus.冻结
  }
}
const validEndDate = (rule: any, val: any, cb: (arg0?: string) => void) => {
  const nowDate = new Date(`${ikDate.toDate()} 00:00:00`)
  const eDate = val ? new Date(`${val} 00:00:00`) : null

  if (tenantState.form.status === EStatus.正常) {
    if (eDate && eDate < nowDate) {
      tenantState.form.endDate = ''
      cb('正常状态下，租户结束日期不能早于当前日期')
    }
    else {
      cb()
    }
  }
  else if (tenantState.form.status === EStatus.冻结) {
    if (eDate && eDate >= nowDate) {
      tenantState.form.endDate = ''
      cb('冻结状态下，租户结束日期需早于当前时刻')
    }
    else {
      cb()
    }
  }
  else {
    cb()
  }
}

const tenantRules = {
  name: [{ required: true, message: placeholder.name, trigger: 'blur' }],
  code: [{ required: true, message: placeholder.code, trigger: 'blur' }],
  type: [{ required: true, message: placeholder.type, trigger: 'change' }],
  status: [{ required: true, message: placeholder.status, trigger: 'change' }],
  tenantDomain: [{ required: true, message: placeholder.tenantDomain, trigger: 'blur' }],
  endDate: [
    { trigger: 'change', validator: validEndDate }
  ],
  startDate: [
    { trigger: 'change', validator: validStartDate }
  ]
}
const tenantRef = ref()
const disabledDate = (date: Date) => {
  const today = new Date()
  today.setHours(0, 0, 0, 0) // 将当前时间设置为0点0分0秒
  return date && date.getTime() < today.getTime() // 禁用早于今天日期的日期
}
const handleClose = () => {
  emits('update:visible', false)
  dVisible.value = false
  tenantState.loading = false
  tenantRef.value?.resetFields()
  tenantState.form = { ...props.formKey }
}

const handConfirm = () => {
  tenantRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      tenantState.loading = true
      const params = {
        ...tenantState.form
      }
      const { msg, success } = props.editData
        ? await tenantApi.updateTenant(params)
        : await tenantApi.addTenant(params)
      if (success) {
        msgSuccess(msg)
        handleClose()
        emits('dataChange')
      }
      else {
        msgError(msg)
      }
      tenantState.loading = false
    }
  })
}
watch(
  () => props.visible,
  (bool: boolean) => {
    dVisible.value = bool
    if (bool && props.editData) {
      tenantState.form = { ...props.editData }
      tenantState.title = '修改租户'
    }
    else {
      tenantState.title = '新增租户'
    }
  }
)
</script>

<template>
  <el-dialog
    v-model="dVisible"
    :title="tenantState.title"
    draggable
    :width="dialog.l"
    :close-on-click-modal="false"
    align-center
    @closed="handleClose"
  >
    <el-form
      ref="tenantRef"
      :model="tenantState.form"
      :rules="tenantRules"
      label-width="90px"
      label-position="top"
    >
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="租户名称" prop="name">
            <el-input
              v-model.trim="tenantState.form.name"
              :placeholder="placeholder.name"
              :maxlength="lenShort"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租户Code" prop="code">
            <el-input
              v-model.trim="tenantState.form.code"
              :maxlength="lenName"
              show-word-limit
              :disabled="!!props.editData"
              :placeholder="placeholder.code"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="租户类型" prop="type">
            <el-radio-group v-model="tenantState.form.type" size="large">
              <el-radio label="NORMAL">普通租户</el-radio>
              <el-radio label="MASTER">主租户</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租户状态" prop="status">
            <el-radio-group v-model="tenantState.form.status" size="large">
              <el-radio label="NORMAL">正常</el-radio>
              <el-radio label="FREEZE">冻结</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="租户域名" prop="tenantDomain">
        <el-input
          v-model.trim="tenantState.form.tenantDomain"
          :maxlength="lenContent"
          show-word-limit
          :placeholder="placeholder.tenantDomain"
        />
      </el-form-item>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="tenantState.form.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              :placeholder="placeholder.startDate"
              @change="checkStartDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="tenantState.form.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
              :placeholder="placeholder.endDate"
              @change="checkEndDate"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">
        {{ t("action.cancel") }}
      </el-button>
      <el-button type="primary" :loading="tenantState.loading" @click="handConfirm">
        {{ t("action.sure") }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-input__wrapper {
  width: 100% !important;
}
</style>
